package org.bjf.springboot.utils;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;

/**
 * Created by binjinfeng on 2017/6/1.
 */
public class RSAUtil {

  public static final String KEY_ALGORTHM = "RSA";

  /**
   * 用私钥加密
   *
   * @param data 加密数据
   * @param key 密钥
   */
  public static byte[] encryptByPrivateKey(byte[] data, String key) throws Exception {
    //解密密钥
    byte[] keyBytes = Base64.decode(key);
    //取私钥
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
    Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

    //对数据加密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, privateKey);

    return cipher.doFinal(data);
  }

  /**
   * 用私钥解密 * @param data 	加密数据
   *
   * @param key 密钥
   */
  public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception {
    //对私钥解密
    byte[] keyBytes = Base64.decode(key);

    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
    Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    //对数据解密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    return cipher.doFinal(data);
  }

  /**
   * 用公钥加密
   *
   * @param data 加密数据
   * @param key 密钥
   */
  public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception {
    //对公钥解密
    byte[] keyBytes = Base64.decode(key);
    //取公钥
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
    Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

    //对数据解密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    return cipher.doFinal(data);
  }

  /**
   * 用公钥解密
   *
   * @param data 加密数据
   * @param key 密钥
   */
  public static byte[] decryptByPublicKey(byte[] data, String key) throws Exception {
    //对私钥解密
    byte[] keyBytes = Base64.decode(key);
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
    Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

    //对数据解密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, publicKey);

    return cipher.doFinal(data);
  }
}
